package com.dgshanger.sanhxiaofeisc

import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.widget.ImageButton
import android.widget.RadioButton
import cn.jpush.android.api.JPushInterface
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ToastUtils
import com.dgshanger.sanhxiaofeisc.common.AppApi
import com.dgshanger.sanhxiaofeisc.common.Constants
import com.dgshanger.sanhxiaofeisc.common.Constants.KEY_INTENT_MAIN
import com.dgshanger.sanhxiaofeisc.entity.PushExtraEntity
import com.dgshanger.sanhxiaofeisc.ui.home.HomeFragment
import com.dgshanger.sanhxiaofeisc.ui.home.activity.PayResultActivity
import com.dgshanger.sanhxiaofeisc.ui.nearby.NearbyFragment
import com.dgshanger.sanhxiaofeisc.ui.person.MessageActivity
import com.dgshanger.sanhxiaofeisc.ui.person.PayForDetailActivity
import com.dgshanger.sanhxiaofeisc.ui.person.PersonFragment
import com.dgshanger.sanhxiaofeisc.ui.recharge.RechargeFragment
import com.google.gson.Gson
import com.jude.swipbackhelper.SwipeBackHelper
import com.xx.baseutilslibrary.common.XxResourceUtil
import com.xx.baseutilslibrary.network.rx.RxHelper
import com.xx.baseutilslibrary.network.rx.XxBaseHttpObserver
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*


class MainActivity : AppCompatActivity() {

    companion object {
        const val INDEX_HOME = 0
        const val INDEX_PERSON = 3//个人中心
    }

    protected lateinit var mContext: Context
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mContext = this
        beforeSetContentView()
        setContentView(getActivityLayoutId())
        afterSetContentView()
    }

    /**
     * 在设置ContenView之前执行的操作
     * 需要时复写
     */
    fun beforeSetContentView() {}


    /**
     * 在设置ContenView之后执行的操作
     * 需要时复写
     */
    protected fun afterSetContentView() {
        initData()
        initEvent()

        //初始化返回按钮
        val id = XxResourceUtil.getId(mContext, "ib_back")
        val ibBack = findViewById<ImageButton>(id)
        ibBack?.setOnClickListener {
            finish()
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun onMessageChange(showMessage: String) {
        when (showMessage) {
            "showMessage" -> {
                tv_message.visibility = View.VISIBLE
                tv_message.text = Constants.getUnReadMessage().toString()
            }
            "readMsg" -> tv_message.visibility = View.GONE
        }
    }

    private var fragments: ArrayList<Fragment?>? = null
    private lateinit var mTimer: Timer

    fun getActivityLayoutId(): Int = R.layout.activity_main

    override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }

    override fun onStop() {
        EventBus.getDefault().unregister(this)
        super.onStop()
    }

    fun initEvent() =
            radio.setOnCheckedChangeListener { _, checkedId ->
                showFragment(checkedId)
                supportFragmentManager.popBackStack()
            }

    /**
     * 显示Fragment
     */
    private fun showFragment(checkedId: Int) {
        val fragmentTransaction = supportFragmentManager.beginTransaction()
        for (i in fragments!!.indices) {
            val fragment = fragments!![i]
            if (i == checkedId) {
                //先检查Fragment是否创建
                if (fragment == null) {
                    when (i) {
                        0 -> fragments!![i] = HomeFragment()
                        1 -> fragments!![i] = NearbyFragment()
                        2 -> fragments!![i] = RechargeFragment()
                        3 -> fragments!![i] = PersonFragment()
                    }
                    //添加到事物
                    fragmentTransaction.add(R.id.container, fragments!![i])
                }
                fragmentTransaction.show(fragments!![i])
            } else {
                if (fragment != null) {
                    fragmentTransaction.hide(fragment)
                }
            }
        }
        fragmentTransaction.commit()
    }

    /**
     *初始化Fragments
     */
    private fun initFragments() {
        if (fragments == null) {
            //初始化只生成首页碎片
            fragments = arrayListOf(HomeFragment(), null, null, PersonFragment())
        }
        supportFragmentManager
                .beginTransaction()
                .add(R.id.container, fragments!![3])
                .add(R.id.container, fragments!![0])
//                .add(R.id.container, fragments!![1])
//                .add(R.id.container, fragments!![2])
                .commit()

        showFragment(0)
    }

    var isExit: Boolean? = false//是否退出登录
    /**
     * 双击返回桌面
     */
    private fun back2exit() {
        if (isExit!!) {
            ActivityUtils.finishAllActivities(true)
        }
        isExit = true
        ToastUtils.showShort(getString(R.string.Click_back_to_the_desktop_again))
        Timer().schedule(object : TimerTask() {
            override fun run() {
                isExit = false
            }
        }, 1500)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            back2exit()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }


    fun initData() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.statusBarColor = ContextCompat.getColor(mContext, R.color.colorWhite)
        }

        //重置RadioGroup子项id
        for (i in 0 until radio.childCount) {
            radio!!.getChildAt(i)!!.id = i
        }
        initFragments()
        radio.check(INDEX_HOME)
        putPayToken()//每30分钟刷新payToken
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)

        val intExtra = intent!!.getIntExtra(KEY_INTENT_MAIN, INDEX_HOME)
        (radio.getChildAt(intExtra) as RadioButton).isChecked = true

        val extras = intent.getStringExtra(JPushInterface.EXTRA_EXTRA)
        val pushExtraEntity = Gson().fromJson(extras, PushExtraEntity::class.java)
        if (TextUtils.isEmpty(extras) || pushExtraEntity == null) {
            return
        }
        var mIntent: Intent? = null
        if (PushExtraEntity.CODE_NEW_MESSAGE == pushExtraEntity.getPush_code()) {
            //新消息
            mIntent = Intent(mContext, MessageActivity::class.java)
            mIntent.putExtra(Constants.KEY_INTENT_MSG_ID, pushExtraEntity.getRecord_id())
        } else if (PushExtraEntity.CODE_PAY_FOR == pushExtraEntity.getPush_code()) {
            //收到代付申请
            mIntent = Intent(mContext, PayForDetailActivity::class.java)
            mIntent.putExtra(Constants.KEY_INTENT_MSG_ID, pushExtraEntity.getRecord_id())
        } else if (PushExtraEntity.CODE_PAY_SUCCESS == pushExtraEntity.getPush_code()) {
            //付款成功
            mIntent = Intent(mContext, PayResultActivity::class.java)
            mIntent.putExtra("orderId", pushExtraEntity.getRecord_id())
        }
        if (mIntent != null) {
            startActivity(mIntent)
        }
    }

    private fun putPayToken() {
        mTimer = Timer()
        mTimer.schedule(object : TimerTask() {
            override fun run() {
                AppApi.Api().payToken
                        .compose(RxHelper.io_main())
                        .subscribe(object : XxBaseHttpObserver<String>() {
                            override fun onCompleted(msg: String?, entity: String?) {
                                Constants.putPayToken(entity)
                            }

                            override fun onError(error: String?) {
                            }

                            override fun onStart() {
                            }

                            override fun onFinish() {
                            }

                        })
            }
        }, 0, 1000 * 60 * 30)

    }

    override fun onDestroy() {
        super.onDestroy()
        mTimer.cancel()
    }


}


